import Taro, { Component } from '@tarojs/taro'
import { View, Image, Text } from '@tarojs/components'

import './index.scss'

import {get as getGlobalData } from '../../static/js/global_data'
import base from '../../static/js/base'
import common from '../../service/common'


import NumInput from '../numInput'


class Index extends Component {
    static options = {
        addGlobalClass: true
    }
    static defaultProps = {
        goodsInfo: null,
        goodsInfoType: 0, // 0、调接口加入购物车 1、缓存加入购物车
        onGetScope() {}, //获取该组件ref，便于父组件调用内部方法
        onGetGoodsDatilsGG() {}, //从商品规格更新商品详情数据
        onAddGoods() {}, // 点击确定
    }
    constructor() {
        super(...arguments)
    }
    state = {
        isShow: false,
        canSubmit: true, //是否可以提交数据创建订单的开关
        goodsType: 0, //订单创建方式---0是加入购物车--1是立即购买--2是拼团活动中的单独购买不用优惠---3是拼团
        N_NUM: 1,
        imgUrl: getGlobalData('domainImg'), //图片前缀
        fPrice: 0, //优惠金额
        integral: 0, //积分
        salemodel: null, //当前活动
        sType: null, //优惠方式--0--无优惠，2--秒杀，3--满减，5--积分，12--打折，pinTuan--拼团（当拼团时，优惠金额又为0的时候则代表订单创建方式为2）
        newLvgg: null, //商品规格
        joinData: null, //当前拼团数据
        N_SPV_ID_Arr: { //当前选择的规格，该数据最多三种规格，无选择时传0   用于传入701b接口的数据
            Spv1: 0,
            Spv2: 0,
            Spv3: 0,
        },
        checked: 0,
        checkedList : ''
    }
    componentWillMount() {}

    componentDidMount() {
        this.props.onGetScope(this)
    }

    componentWillUnmount() {}

    componentDidShow() {}

    componentDidHide() {}
    boxClick(e) {
        //为盒子添加一个点击事件 阻止事件冒泡
        e.stopPropagation()
    }
    isJsonStr(str) {
        /* 判断是否未JSON字符串 */
        try {
            if (typeof JSON.parse(str) == "object") {
                return true;
            }
        } catch (e) {}
        return false;
    }
    showCut(d) {
        //此处做一个深拷贝，以免更改到父组件的数据
        const { goodsInfo } = this.props;
        let sData = {
            isShow: !this.state.isShow,
        }
        if (d != 0 && d) {
            let data = JSON.parse(JSON.stringify(d))
            sData['goodsType'] = data.type ? data.type : 0;
            sData['fPrice'] = data.fPrice;
            sData['integral'] = data.integral;
            sData['sType'] = data.sType;
            sData['newLvgg'] = data.lvgg;
            sData['salemodel'] = data.salemodel;
            sData['joinData'] = data.joinData;
            sData['checkedList'] =  goodsInfo.skuList[0];
            /* if (data.lvgg && data.lvgg.length > 0) {
            	sData['canSubmit'] = false;
            } */
        } else {
            sData['N_SPV_ID_Arr'] = { Spv1: 0, Spv2: 0, Spv3: 0, }
            sData['newLvgg'] = null;
            sData['sType'] = null;
        }
        console.log(this.state.checkedList)
        this.setState(sData)
    }


    //没做的-----------------------------------------
    onAddShopNum(bNo, types) {
        //获取创建订单的数量
        // this.setState({
        // 	N_NUM: 1
        // })
        const { goodsInfo} = this.props;
        let { N_NUM,checked } = this.state;
        if (types == 'add') { // +
            if (this.state.N_NUM >=  goodsInfo.skuList[checked]) {
                base.showToast('商品库存不足了！', 'none')
                return
            }
            N_NUM++
        }
        if (types == 'minus') { // -
            if (this.state.N_NUM == 1) {
                base.showToast('不能再减了！', 'none')
                return
            }
            N_NUM--
        }
        this.setState({ N_NUM })
    }
    onAddGoods() {
            /* 数据都准备好了 */
            const { goodsType, N_NUM, canSubmit, salemodel, sType, N_SPV_ID_Arr, joinData } = this.state;
            const { goodsInfo, goodsInfoType } = this.props;
            // sType: null,//优惠方式--0--无优惠，2--秒杀，3--满减，5--积分，12--打折，pinTuan--拼团（当拼团时，优惠金额又为0的时候则代表订单创建方式为2）
            //salemodel优惠数据--salemodel.SaleId优惠活动id
            // goodsType: 0,//订单创建方式---0是加入购物车--1是立即购买--2是拼团活动中的单独购买不用优惠---3是拼团----4是参加拼团
            // canSubmit: true,//是否可以提交数据创建订单的开关---暂时未使用
            // N_SPV_ID_Arr--当前选择的规格ID数据
            // joinData参加拼团的数据----数据接口说明------https://www.showdoc.cc/307979785599018?page_id=1762769758844284--附表2说明
            if (goodsInfoType == 1) { // 加入购物车缓存
                this.props.onAddGoods(goodsInfo, N_NUM, salemodel)
                this.setState({
                    isShow: false,
                    goodsType: 0, //订单创建方式---0是加入购物车--1是立即购买--2是拼团活动中的单独购买不用优惠---3是拼团
                    N_NUM: 1,
                    fPrice: 0, //优惠金额
                    integral: 0, //积分
                    salemodel: null, //当前活动
                    sType: null, //优惠方式--0--无优惠，2--秒杀，3--满减，5--积分，12--打折，pinTuan--拼团（当拼团时，优惠金额又为0的时候则代表订单创建方式为2）
                    newLvgg: null, //商品规格
                    joinData: null, //当前拼团数据
                    N_SPV_ID_Arr: { //当前选择的规格，该数据最多三种规格，无选择时传0   用于传入701b接口的数据
                        Spv1: 0,
                        Spv2: 0,
                        Spv3: 0,
                    },
                })
                this.showCut()
                return
            }
            if (!canSubmit) {
                return false;
            }
            if (salemodel) {
                /* 普通优惠 --传入优惠id*/
                this.state.mkid = salemodel.SaleId //促销活动类型(1分时促销 2秒杀 3立减 4全场折扣 5积分活动)
                this.state.mkcid = sType //促销活动编号
                this.changeCar(goodsInfo, N_NUM, goodsType)
                console.log(salemodel, sType, N_SPV_ID_Arr, '优惠')
            } else {
                if (sType == 'pinTuan') {
                    /* 拼团 */
                    if (goodsType == 2) { /* 拼团--单独购买 */
                        this.changeCar(goodsInfo, N_NUM, 1)
                    } else if (goodsType == 3) { /* 底部拼团购买按钮 */
                        Taro.navigateTo({
                            url: '/pages/orderSubmitMarketing/index?goodType=pintuan&totalNum=' + this.state.N_NUM
                        })
                    } else if (goodsType == 4) { /* 拼团购买--此处可能要传入参与拼团的拼团号-数据再joinData中 已经有人拼团了的 */
                        Taro.navigateTo({
                            url: `/pages/orderSubmitMarketing/index?goodType=pintuan&totalNum=${this.state.N_NUM}&pintuanGslistdt=${JSON.stringify(joinData)}`
                        })
                    }
                } else {
                    /* 普通购买--无优惠 */
                    this.changeCar(goodsInfo, N_NUM, goodsType)
                }
            }
        }
        // 加入购物车、立即购买
    changeCar(goodsInfo, N_NUM, goodsType) {
        const { checked } = this.state;
        common.changeCar(this, 'GO0001', goodsInfo.skuList[checked], N_NUM, goodsType, (res) => {
            this.showCut()
            if (goodsType == 0) {
                base.showToast('加入购物车' + res.msg)
            } else {
                Taro.navigateTo({
                    url: `/pages/orderSubmitMarketing/index?totalNum=${res.cartnum}&&cids=${res.cartid}`
                })
            }
        })
    }
    setGg(index, id) {
        //设置当前选择的规格
        const { N_SPV_ID_Arr, newLvgg, checked } = this.state;
        const { goodsInfo, goodsInfoType } = this.props;
        newLvgg.map((val, inum) => {
            if (index == inum) {
                val.speValues.map((v) => {
                    if (v.isChoose) {
                        v.isChoose = false
                    }
                })
                val.speValues.map((value, inNum) => {
                    if (value.speValueId == id) {
                        newLvgg[inum].speValues[inNum].isChoose = true;
                        N_SPV_ID_Arr['Spv' + (index + 1)] = id;
                    }
                })

            }
        })
        let checkeds = '';
        if (N_SPV_ID_Arr.Spv3 > 0) {
            checkeds = N_SPV_ID_Arr.Spv1 + ',' + N_SPV_ID_Arr.Spv1 + ',' + N_SPV_ID_Arr.Spv3
        } else if (N_SPV_ID_Arr.Spv2 > 0) {
            checkeds = N_SPV_ID_Arr.Spv1 + ',' + N_SPV_ID_Arr.Spv2
        } else if (N_SPV_ID_Arr.Spv1 > 0) {
            checkeds = N_SPV_ID_Arr.Spv1
        }
        goodsInfo.skuList.forEach((element,index) => {
            if (checkeds && element.speValueIds == checkeds) {
                this.setState({
                    checked: index
                })
            }
        });


        this.setState({ N_SPV_ID_Arr, newLvgg }, () => {
            let chooseLength = 0;
            this.state.newLvgg.map((val) => {
                val.speValues.map((v) => {
                    if (v.isChoose) {
                        chooseLength++
                    }
                })
            })


            console.log(N_SPV_ID_Arr, "======================")
                //选择的规格与获取到的规格数量相同时则请求数据
                // if (chooseLength >= newLvgg.length) {
                // 	/* this.setState({
                // 		canSubmit: true
                // 	}) */
                // 	this.props.onGetGoodsDatilsGG(N_SPV_ID_Arr);
                // }
        })
    }
    getSTOCK(STOCK) {
        if (STOCK > 15) {
            return '库存充足'
        } else if (STOCK <= 15) {
            return '库存紧张'
        } else {
            return '库存不足'
        }
    }
    render() {
        // console.log('goodsClose---------------------')
        // console.log(this.props)
        // console.log(this.state)
        const { isShow, imgUrl, fPrice, integral, newLvgg, canSubmit, checked } = this.state;
        const { goodsInfo } = this.props;
        return ( <View > {
                    isShow ? ( <View className = 'shopCloseModal'
                        onClick = { this.showCut.bind(this, 0) } > {
                            goodsInfo ? ( <View className = 'box'
                                onClick = { this.boxClick.bind(this) } >
                                <View className = 'head' >
                                <View className = 'shopImg' >
                                <Image className = 'headImg'
                                src = { imgUrl + goodsInfo.skuList[0].imageUrl } > </Image> </View > 
								<View className = 'center' >
                                <View className = 'center1' > { goodsInfo.goodsName } </View> 
								<View className = 'center2' > { goodsInfo ? this.getSTOCK(goodsInfo.skuList[checked].stock) : '' } </View> 
                                {
                                fPrice != 0 && fPrice ? ( <View className = 'center3' >
                                    <View className = 'cen1' > ￥{ fPrice } </View> { integral != 0 && integral ? < View className = 'cen3' > +{ integral }积分 </View> : ''} 
                                    <View className = 'cen2' > 原价 : ￥{ goodsInfo.skuList[checked].oldPrice ? goodsInfo.skuList[checked].oldPrice : goodsInfo.skuList[checked].salePrice } </View> 
									</View >
                                ) : ( < View className = 'center3' >
                                            <View className = 'cen1' > ￥{ goodsInfo.skuList[checked].salePrice ? goodsInfo.skuList[checked].salePrice : goodsInfo.skuList[checked].oldPrice } </View>
                                      </View>
                                )
                            } </View> <View className = 'shopRight' >
                            <View className = 'close' >
                            <Text className = 'iconfont icon-close'
                            onClick = { this.showCut.bind(this, 0) } > </Text> 
							</View > <View className = 'numAdd' >
                            <NumInput type = 'square'
                            nums = { this.state.N_NUM }
                            onChangeCartNum = { this.onAddShopNum.bind(this) } > </NumInput> </View > 
							</View> </ View > {
                                newLvgg && newLvgg.length > 0 ? ( <View className = 'closeBody' > {
                                        newLvgg.map((val, i) => ( <View className = 'bodyItem'
                                            key = { 'itBox' + i } >
                                            <View className = 'bodyHead' > { val.speName } </View> 
											<View className = 'bodyBody' > {
                                                val.speValues.map((value, index) => ( <View onClick = { this.setGg.bind(this, i, value.speValueId) }
                                                    className = { `spvList ${value.isChoose ? 'isChoose' : 'onChoose'}` }
                                                    key = { 'item' + index } > { value.speValue } </View>
                                                ))
                                            } </View> </View >
                                        ))
                                    } </View>
                                ) : ''
                            } <View className = { `food ${canSubmit ? 'can' : 'foodNoSub'}` }
                            onClick = { this.onAddGoods.bind(this) } > 确定 </View> </View >
                        ): ''
                    } </View>
                ): ''
            } </View>


    )
}
}
export default Index;